package com.ias.agdis_r.temple;

import com.ias.agdis_r.bean.other.AreaBean;
import com.ias.agdis_r.bean.other.LimitBean;
import com.ias.agdis_r.bean.other.TempLabelBean;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.sdcard.SDcard;

import org.xmlpull.v1.XmlPullParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class XmlHelper {

	private TaskTempBean taskViewTemp = null;
	private TaskTempBean NFTaskViewTemp = null;
	private FlightTempBean queryViewTemp = null;
	private static XmlHelper instance = null;

	public static XmlHelper getInstance() {
		if (instance == null) {
			instance = new XmlHelper();
		}
		return instance;
	}

	private String getLoadFileName() {
		// 根据MFG加载模板，如果没有，加载默认模板
		String mfg = "";
		// SysInfoBean sysInfo = JavaBeanManager.getInstance().getSysInfo();
		UserInfoBean userinfo = JavaBeanManager.getInstance().getUserinfo();
		if (null != userinfo) {
			// mfg = sysInfo.getMtfFlag();
			mfg = userinfo.getMfg();
		}

		String loadFileName = SDcard.getSDPATH()
				+ "/IASDataBase/templet/DEFAULT.xml"; // 默认模板
		String fileName = SDcard.getSDPATH() + "/IASDataBase/templet/" + mfg
				+ ".xml"; // 岗位匹配模板
		File file = new File(fileName);
		if (file.exists()) {
			loadFileName = fileName;
		}
		return loadFileName;
	}

	public void loadTaskXML() {
		taskViewTemp = new TaskTempBean();
		try {
			String fileName = getLoadFileName();
			Xml task = new Xml(fileName, "TASK");
			taskViewTemp.type = task.string("type");
			Map<String, TaskDataTemp> taskDataList = new HashMap<String, TaskDataTemp>();
			taskViewTemp.taskDataList = taskDataList;
			for (Xml node : task.child("NODES").children("NODE")) {
				TaskDataTemp taskData = new TaskDataTemp();
				taskData.status = node.string("type");

				Map<String, AodTypeItem> aodlist = new HashMap<String, AodTypeItem>();

				for (Xml aod : node.child("DATA").children("AOD")) {
					// System.out.println("aod type: " + aod.string("type"));
					AodTypeItem aodTypeItem = new AodTypeItem();
					aodTypeItem.type = aod.string("type");
					aodTypeItem.group1 = new LinkedHashMap<String, TempLabelBean>();
					for (Xml item : aod.child("GROUP1").children("ITEM")) {

						TempLabelBean taskLabelBean = new TempLabelBean();
						// 标签类型
						taskLabelBean.setType(item.string("type"));
						// 标签URL
						taskLabelBean.setUrl(S.valueOf(item.string("url")));
						// 标签显示内容
						taskLabelBean.setContent(item.content());
						aodTypeItem.group1.put(item.string("type"),
								taskLabelBean);

					}
					aodTypeItem.group2 = new LinkedHashMap<String, TempLabelBean>();
					for (Xml item : aod.child("GROUP2").children("ITEM")) {

						TempLabelBean taskLabelBean = new TempLabelBean();
						// 标签类型
						taskLabelBean.setType(item.string("type"));
						// 标签URL
						taskLabelBean.setUrl(S.valueOf(item.string("url")));
						// 标签显示内容
						taskLabelBean.setContent(item.content());
						aodTypeItem.group2.put(item.string("type"),
								taskLabelBean);
					}

					aodlist.put(aodTypeItem.type, aodTypeItem);

				} // aod

				taskData.aodTypeList = aodlist;

				// buttons
				List<ButtonTempBean> buttonList = new ArrayList<ButtonTempBean>();

				for (Xml button : node.child("BUTTONS").children("BUTTON")) {
					ButtonTempBean buttonTemp = new ButtonTempBean();
					buttonTemp.type = button.string("type");
					buttonTemp.mapping = button.child("MAPPING").content()
							.trim();
					String confirm = button.child("CONFIRM").content();

					if (confirm.equalsIgnoreCase("N")) {
						buttonTemp.confirm = false;
					} else {
						buttonTemp.confirm = true;
					}
					buttonTemp.value = button.child("VALUE").content();

					buttonList.add(buttonTemp);
				} // button
				taskData.buttonTemps = buttonList;

				taskDataList.put(taskData.status, taskData);
			} // node
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}

	private String getLoadNFTaskFileName() {
		// 根据MFG加载模板，如果没有，加载默认模板
//		String mfg = "";
//		// SysInfoBean sysInfo = JavaBeanManager.getInstance().getSysInfo();
//		UserInfoBean userinfo = JavaBeanManager.getInstance().getUserinfo();
//		if (null != userinfo) {
//			// mfg = sysInfo.getMtfFlag();
//			mfg = userinfo.getMfg();
//		}

		String loadFileName = SDcard.getSDPATH()
				+ "/IASDataBase/templet/NFDEFAULT.xml"; // 默认模板
//		String fileName = SDcard.getSDPATH() + "/IASDataBase/templet/task/" + mfg
//				+ ".xml"; // 岗位匹配模板
//		File file = new File(fileName);
//		if (file.exists()) {
//			loadFileName = fileName;
//		}
		return loadFileName;
	}

	public void loadNFTaskXML() {
		NFTaskViewTemp = new TaskTempBean();
		try {
			String fileName = getLoadNFTaskFileName();
			Xml task = new Xml(fileName, "TASK");
			NFTaskViewTemp.type = task.string("type");
			Map<String, TaskDataTemp> taskDataList = new HashMap<String, TaskDataTemp>();
			NFTaskViewTemp.taskDataList = taskDataList;
			for (Xml node : task.child("NODES").children("NODE")) {
				TaskDataTemp taskData = new TaskDataTemp();
				taskData.status = node.string("type");

				Map<String, AodTypeItem> aodlist = new HashMap<String, AodTypeItem>();

				for (Xml aod : node.child("DATA").children("AOD")) {
					// System.out.println("aod type: " + aod.string("type"));
					AodTypeItem aodTypeItem = new AodTypeItem();
					aodTypeItem.type = aod.string("type");
					aodTypeItem.group1 = new LinkedHashMap<String, TempLabelBean>();
					for (Xml item : aod.child("GROUP1").children("ITEM")) {

						TempLabelBean taskLabelBean = new TempLabelBean();
						// 标签类型
						taskLabelBean.setType(item.string("type"));
						// 标签URL
						taskLabelBean.setUrl(S.valueOf(item.string("url")));
						// 标签显示内容
						taskLabelBean.setContent(item.content());
						aodTypeItem.group1.put(item.string("type"),
								taskLabelBean);

					}
					aodTypeItem.group2 = new LinkedHashMap<String, TempLabelBean>();
					for (Xml item : aod.child("GROUP2").children("ITEM")) {

						TempLabelBean taskLabelBean = new TempLabelBean();
						// 标签类型
						taskLabelBean.setType(item.string("type"));
						// 标签URL
						taskLabelBean.setUrl(S.valueOf(item.string("url")));
						// 标签显示内容
						taskLabelBean.setContent(item.content());
						aodTypeItem.group2.put(item.string("type"),
								taskLabelBean);
					}

					aodlist.put(aodTypeItem.type, aodTypeItem);

				} // aod

				taskData.aodTypeList = aodlist;

				// buttons
				List<ButtonTempBean> buttonList = new ArrayList<ButtonTempBean>();

				for (Xml button : node.child("BUTTONS").children("BUTTON")) {
					ButtonTempBean buttonTemp = new ButtonTempBean();
					buttonTemp.type = button.string("type");
					buttonTemp.mapping = button.child("MAPPING").content()
							.trim();
					String confirm = button.child("CONFIRM").content();

					if (confirm.equalsIgnoreCase("N")) {
						buttonTemp.confirm = false;
					} else {
						buttonTemp.confirm = true;
					}
					buttonTemp.value = button.child("VALUE").content();

					buttonList.add(buttonTemp);
				} // button
				taskData.buttonTemps = buttonList;

				taskDataList.put(taskData.status, taskData);
			} // node
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}

	public FlightTempBean loadFlightXML() {
		if (queryViewTemp == null) {
			queryViewTemp = new FlightTempBean();
		}
		Xml result = new Xml(SDcard.getSDPATH()
				+ "/IASDataBase/templet/QUERY_RESULT.xml", "RESULT");
		for (Xml node : result.children("AOD")) {
			if (node.string("type").equals("A")) {
				if (queryViewTemp.groupA == null) {
					queryViewTemp.groupA = new LinkedHashMap<String, TempLabelBean>();
				} else {
					queryViewTemp.groupA.clear();
				}
				for (Xml item : node.children("ITEM")) {

					TempLabelBean flightLabelBean = new TempLabelBean();
					// 标签类型
					flightLabelBean.setType(item.string("type"));
					// 标签URL
					flightLabelBean.setUrl(S.valueOf(item.string("url")));
					// 标签内容
					flightLabelBean.setContent(item.content());
					queryViewTemp.groupA.put(item.string("type"),
							flightLabelBean);
				}
			} else if (node.string("type").equals("D")) {
				if (queryViewTemp.groupD == null) {
					queryViewTemp.groupD = new LinkedHashMap<String, TempLabelBean>();
				} else {
					queryViewTemp.groupD.clear();
				}
				for (Xml item : node.children("ITEM")) {

					TempLabelBean flightLabelBean = new TempLabelBean();
					// 标签类型
					flightLabelBean.setType(item.string("type"));
					// 标签URL
					flightLabelBean.setUrl(S.valueOf(item.string("url")));
					// 标签内容
					flightLabelBean.setContent(item.content());
					queryViewTemp.groupD.put(item.string("type"),
							flightLabelBean);
				}
			}
		}

		return queryViewTemp;
	}
	public void loadAreaXML() {
		InputStream in = null;
		OutputStream out = null;
		try
		{
			File f = new File(SDcard.getSDPATH()
					+ "/IASDataBase/area/AREA_XIAN.xml");
			in = new FileInputStream(f);
			if(in!=null)
			{
				XmlPullParser parser = android.util.Xml.newPullParser();
				parser.setInput(in, "utf-8");//设置解析的数据源
				int type = parser.getEventType();
				AreaBean areaBean =null;
				LimitBean limitBean = null;
				String areaType ="";
				List<AreaBean> areaList = null;

				while(type != XmlPullParser.END_DOCUMENT )
				{
					switch (type) {
						case XmlPullParser.START_DOCUMENT://判断当前事件是否是文档开始事件
							break;
						case XmlPullParser.START_TAG:
							if(ParameterModel.AREA_LIST.equals(parser.getName()))
							{
								areaType = parser.getAttributeValue(0);
								if(ParameterModel.LOCK_TYPE_PLACECODE.equals(areaType)) {
									areaList = JavaBeanManager.getInstance().getPlaceAreaList();
								}else if(ParameterModel.LOCK_TYPE_GTNAME.equals(areaType)){
									areaList = JavaBeanManager.getInstance().getGtnAreaList();
								}else if(ParameterModel.LOCK_TYPE_BLT.equals(areaType)){
									areaList = JavaBeanManager.getInstance().getBltAreaList();
								}else if(ParameterModel.LOCK_TYPE_PSN.equals(areaType)){
									areaList = JavaBeanManager.getInstance().getPsnAreaList();
								}
								areaList.clear();
							}else if(ParameterModel.AREA.equals(parser.getName())){
								areaBean = new AreaBean();
							}
							else if(ParameterModel.ID.equals(parser.getName())){
								String id = parser.nextText();
								areaBean.setId(id);
							}
							else if(ParameterModel.KEY.equals(parser.getName())){
								String key = S.valueOf(parser.nextText());
								areaBean.setKey(key);
							}
							else if(ParameterModel.NAME.equals(parser.getName())){
								String name = parser.nextText();
								areaBean.setName(name);
							}
							else if(ParameterModel.LIMIT.equals(parser.getName())){
								limitBean = new LimitBean();
							}
							else if(ParameterModel.LIMIT_TYPE.equals(parser.getName())){
								String limit_type = parser.nextText();
								limitBean.setType(limit_type);
							}
							else if(ParameterModel.LIMIT_INCLUDE.equals(parser.getName())){
								String limit_include = parser.nextText();
								if(S.isNotEmpty(limit_include)){
									String[] includeArray = limit_include.split(",");
									for(String includeItem:includeArray){
										limitBean.getIncludeSet().add(includeItem);
									}
								}
							}
							else if(ParameterModel.LIMIT_START.equals(parser.getName())){
								String limit_start = parser.nextText();
								limitBean.setStart(limit_start);
							}
							else if(ParameterModel.LIMIT_END.equals(parser.getName())){
								String limit_end = parser.nextText();
								limitBean.setEnd(limit_end);
							}
							break;
						case XmlPullParser.END_TAG:{
							if(ParameterModel.LIMIT.equals(parser.getName())){
								areaBean.getLimitList().add(limitBean);
							}else if(ParameterModel.AREA.equals(parser.getName())){
								areaList.add(areaBean);
							}else if(ParameterModel.AREA_LIST.equals(parser.getName())){
//								System.out.println("区域-读取区域信息：");
//								for(AreaBean areaBean2:areaList){
//									System.out.println("区域-基本信息ID:"+areaBean2.getId()+"|KEY:"+areaBean2.getKey()+"|NAME:"+areaBean2.getName());
//									List<LimitBean> limitList = areaBean2.getLimitList();
//									for(LimitBean limit:limitList){
//										System.out.println("区域-限制TYPE:"+limit.getType()+"|START:"+limit.getStart()+"|END:"+limit.getEnd()+"|INCLUDE"+limit.getIncludeSet().toString());
//									}
//								}
							}
							break;
						}
					}
					type = parser.next();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				if(in!=null)
				{
					in.close();
					in = null;
				}
				if(out!=null)
				{
					out.close();
					in = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	};
		public FlightTempBean getQueryViewTemp() {
		return queryViewTemp;
	}

	public TaskTempBean getTaskViewTemp() {
		return taskViewTemp;
	}

	public TaskTempBean getNFTaskViewTemp() {
		return NFTaskViewTemp;
	}

	public void destoryTaskViewTemp() {
		taskViewTemp = null;
	}

}
